package com.example.restaurantclient.Activity;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

import android.Manifest;
import android.app.Dialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.graphics.Typeface;
import android.location.Address;
import android.location.Geocoder;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.SDKInitializer;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.InfoWindow;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.MyLocationConfiguration;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.navi.BaiduMapAppNotSupportNaviException;
import com.baidu.mapapi.navi.BaiduMapNavigation;
import com.baidu.mapapi.navi.NaviParaOption;
import com.example.restaurantclient.LikeButton.LikeButton;
import com.example.restaurantclient.LikeButton.OnLikeListener;
import com.example.restaurantclient.R;
import com.example.restaurantclient.WheelDialog.HeightWheelDialog;

import java.io.IOException;
import java.util.List;
import java.util.Locale;

public class QueueUpInfoActivity extends AppCompatActivity implements OnLikeListener {
    private LocationClient mLocationClient = null;

    private MapView mapView;
    private BaiduMap baiduMap;
//    private double latitude=38.865106;
//    private double longtitude=115.495957;
    private double latitude;
    private double longtitude;
    private ImageView btn_phone;
    private TextView queueUpInTime;
    private TextView peopleNum;
    private LinearLayout linearPeopleNum;
    private HeightWheelDialog mHeight_Dialog1;
    private HeightWheelDialog.HeightWheelDialogcallback mCallback_height1;
    private LinearLayout navigationText;
    //收藏按钮
    private LikeButton starButton;

    //导航
    //起始点经纬度
    private double startLon;
    private double startLat;

    private NaviParaOption para;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //initialize方法必须在界面显示之前调用，参数必须是应用程序级别的环境上下文
        SDKInitializer.initialize(getApplicationContext());
        setContentView(R.layout.activity_queue_up_info);
        //导航
        para = new NaviParaOption();
        //定位
        //创建定位客户端对象，参数要求是应用程序级别的环境上下文对象
        mLocationClient= new LocationClient(getApplicationContext());
        //动态申请权限
        ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.ACCESS_FINE_LOCATION},100);

        SharedPreferences sp = getSharedPreferences ("data",MODE_PRIVATE);
        latitude= sp.getFloat("latitude",0);
        longtitude= sp.getFloat("longtitude",0);
        System.out.println(latitude+";"+longtitude);
        //导航
        navigationText=findViewById(R.id.queue_up_navigation);
        navigationText.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                para.startPoint(new LatLng(startLat, startLon));
                para.startName("从这里开始");
                para.endPoint(new LatLng(latitude, longtitude));
                para.endName("到这里结束");
                BaiduMapNavigation.setSupportWebNavi(false);
                try {
                    BaiduMapNavigation.openBaiduMapNavi(para, QueueUpInfoActivity.this);
                } catch (BaiduMapAppNotSupportNaviException e) {
                    e.printStackTrace();
                    Toast.makeText(QueueUpInfoActivity.this, "您尚未安装百度地图app", Toast.LENGTH_SHORT).show();
                }
            }
        });


        btn_phone=findViewById(R.id.btn_phone);

        queueUpInTime=findViewById(R.id.queue_up_in_time);
        peopleNum=findViewById(R.id.text_peoplenum);
        linearPeopleNum=findViewById(R.id.people_linear_num);
        queueUpInTime=findViewById(R.id.queue_up_in_time);
        queueUpInTime.setTypeface(Typeface.SANS_SERIF, Typeface.BOLD_ITALIC);
        starButton= (LikeButton)this.findViewById(R.id.star_button);
        starButton.setOnLikeListener(this);
        queueUpInTime.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
                Intent intent1=new Intent(QueueUpInfoActivity.this,QueueUpSuccessActivity.class);
                startActivity(intent1);
            }
        });
//        queueUpInTime.setTypeface(Typeface.SANS_SERIF, Typeface.BOLD_ITALIC);
        //地图界面视图对象
        mapView = findViewById(R.id.map_view);
        //获取百度地图控制器类对象
        baiduMap = mapView.getMap();
        //修改比例尺
        MapStatusUpdate msu = MapStatusUpdateFactory.zoomTo(19.0f);//进入之后的默认比例尺缩放大小
        baiduMap.setMapStatus(msu);
//        //实现定位功能
//        //创建定位客户端对象，参数要求是应用程序级别的环境上下文对象
//        mLocationClient= new LocationClient(getApplicationContext());
//        //动态申请权限
//        ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.ACCESS_FINE_LOCATION},100);
        addMarkerOverlay();
        btn_phone.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(Intent.ACTION_DIAL);
                Uri data = Uri.parse("tel:" + "0312-103789");
                intent.setData(data);
                startActivity(intent);
            }
        });
        linearPeopleNum.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                height_Dialog_Display1();
            }
        });

        mCallback_height1 = new HeightWheelDialog.HeightWheelDialogcallback() {
            @Override
            public void dialogdo(String string, Dialog dialog) {
                peopleNum.setText(string);
            }
        };
    }
    //收藏按钮点击
    @Override
    public void liked(LikeButton likeButton) {
        Toast.makeText(this, "已收藏!", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void unLiked(LikeButton likeButton) {
        Toast.makeText(this, "取消收藏!", Toast.LENGTH_SHORT).show();
    }

    //添加标注覆盖物（在地图界面某个坐标点显示小图标）
    public void addMarkerOverlay(){
        // 定义Maker坐标点
        LatLng point = new LatLng(latitude, longtitude);
        // 构建Marker图标
        BitmapDescriptor bitmap = BitmapDescriptorFactory
                .fromResource(R.drawable.marker);
        // 构建MarkerOption，用于在地图上添加Marker
        OverlayOptions option = new MarkerOptions()
                .position(point)// 设置marker的位置
                .icon(bitmap);  // 必须设置marker图标
        //在地图上添加Marker，并显示
        Marker marker = (Marker)baiduMap.addOverlay(option);
        //移动地图界面显示到当前位置
        MapStatusUpdate update=MapStatusUpdateFactory.newLatLng(point);
        //移动地图界面
        baiduMap.animateMapStatus(update);
        baiduMap.setOnMarkerClickListener(new BaiduMap
                .OnMarkerClickListener() {
            @Override
            public boolean onMarkerClick(Marker marker) {
                final LatLng latLng = marker.getPosition();
                Toast.makeText(QueueUpInfoActivity.this,
                        latLng.toString(),
                        Toast.LENGTH_SHORT)
                        .show();
                return false;
            }
        });

    }
    public void height_Dialog_Display1() {
        if (mHeight_Dialog1 == null) {
            mHeight_Dialog1 = new HeightWheelDialog(this, getWindowManager());
            mHeight_Dialog1.setCanceledOnTouchOutside();
        }
        mHeight_Dialog1.setDialogCallback(mCallback_height1);
        mHeight_Dialog1.show();
    }
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        //grantResults数组当中存储的是用户选择的结果，0表示允许，-1表示拒绝
        if(requestCode==100&&grantResults[0]==0){
            //创建locationclientoption对象
            LocationClientOption locationClientOption=new LocationClientOption();
            //配置定位参数
            //设置打开GPS
            locationClientOption.setOpenGps(true);
            //设置坐标系类型
            locationClientOption.setCoorType("bd09ll");//百度的经纬度坐标系
            //设置采用的定位模式(建议使用低功耗的定位模式)
            locationClientOption.setLocationMode(LocationClientOption.LocationMode.Battery_Saving);
//            locationClientOption.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);
            //将定位参数应用到定位客户端
            mLocationClient.setLocOption(locationClientOption);
            //设置定位成功的监听器(实现异步定位操作，定位成功后会自动调用接口中的方法)
            mLocationClient.registerLocationListener(new BDAbstractLocationListener() {
                @Override
                public void onReceiveLocation(BDLocation bdLocation) {
                    //定位成功后自动执行:定位成功后位置信息保存在BDLocation对象中
                    startLat=bdLocation.getLatitude();//纬度
                    startLon=bdLocation.getLongitude();//经度
                    System.out.println("纬度"+latitude+"经度"+longtitude);
//                    int code=bdLocation.getLocType();//获取定位错误码
//                    List<Address> result = null;
//                    if (bdLocation != null) {
//                        Geocoder gc = new Geocoder(QueueUpInfoActivity.this, Locale.getDefault());
//                        try {
//                            result = gc.getFromLocation(bdLocation.getLatitude(),
//                                    bdLocation.getLongitude(), 1);
//                        } catch (IOException e) {
//                            e.printStackTrace();
//                        }
//                    }
//                    Log.e("定位成功","定位结果"+code+"纬度"+latitude+"经度"+longtitude+"城市名字"+result.get(0).getLocality());
//                    //移动地图界面显示到当前位置
//                    LatLng point=new LatLng(latitude1,longtitude1);
//                    MapStatusUpdate update=MapStatusUpdateFactory.newLatLng(point);
//                    //移动地图界面
//                    baiduMap.animateMapStatus(update);
//                    //在当前位置添加圆点覆盖物
//                    BitmapDescriptor descriptor= BitmapDescriptorFactory.fromResource(R.drawable.marker);
//                    MarkerOptions options=new MarkerOptions().position(point).icon(descriptor);
//                    baiduMap.addOverlay(options);
//                    //添加定位图层
//                    //(1)配置定位图层
//                    MyLocationConfiguration configuration=new MyLocationConfiguration(MyLocationConfiguration.LocationMode.COMPASS,//定位图层的显示
//                            true,//显示方向信息
//                            null);//使用默认小图标
//
//                    //在地图界面显示定位图层
//                    baiduMap.setMyLocationConfiguration(configuration);
//                    baiduMap.setMyLocationEnabled(true);
//                    //（2）配置定位数据
//                    MyLocationData data=new MyLocationData.Builder()
//                            .latitude(latitude1)
//                            .longitude(longtitude1)
//                            .build();
                    //将定位数据设置到地图
//                    baiduMap.setMyLocationData(data);
                }
            });
            //开启定位
            mLocationClient.start();
        }
    }
    @Override
    protected void onResume() {
        super.onResume();
        mapView.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        mapView.onPause();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mapView.onDestroy();
    }
}
